package com.yuneec.droneservice.protocol.analysis;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

/**
 * Created by zd.zhang on 2017/5/12.
 */

public abstract class UsbMonitor extends BroadcastReceiver {
    private final static String ACTION = "android.hardware.usb.action.USB_STATE";
    private Context context;
    private IntentFilter filter;

    public UsbMonitor(Context context) {
        this.context = context;
        filter = new IntentFilter();
        filter.addAction(ACTION);
    }


    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(ACTION)) {
            boolean connected = intent.getExtras().getBoolean("connected");
            if (connected) {
                onAttach();
            } else {
                onDetach();
            }
        }
    }

    public synchronized void start() {
        if (context != null) {
            context.registerReceiver(this, filter);
            onStart(context);
        }
    }

    public synchronized void close() {
        if (context != null) {
            context.unregisterReceiver(this);
            onDestroy(context);
            context = null;
            filter = null;
        }
    }

    abstract void onStart(Context context);

    abstract void onAttach();

    abstract void onDetach();

    abstract void onDestroy(Context context);


}
